import 'package:easy_refresh/easy_refresh.dart';
import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:extended_tabs/extended_tabs.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/entity/expert/plan_form/plan_form_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/mode_config.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/view/pick/items/avator_label.dart';
import 'package:sports_new/widgets/focus_button.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/loading/no_data_widget.dart';
import 'package:sports_new/widgets/loading/shimmer_loading_widget.dart';
import 'package:visibility_detector/visibility_detector.dart';
import '../../../controller/expert/plan_form_logic.dart';
import '../../../utils/user.dart';
import '../../../widgets/base/qkd_text.dart';
import '../../../widgets/card.dart';
import '../../home/qkd_carousel_view.dart';

class PlanFormPage extends StatefulWidget {
  const PlanFormPage({super.key});

  @override
  State<PlanFormPage> createState() => _PlanFormPageState();
}

class _PlanFormPageState extends State<PlanFormPage> {
  final logic = Get.put(PlanFormLogic());

  @override
  Widget build(BuildContext context) {
    return GetBuilder<PlanFormLogic>(builder: (logic) {
      return VisibilityDetector(
        key: const Key("planForm"),
        onVisibilityChanged: (VisibilityInfo info) {
          if (!info.visibleBounds.isEmpty && User.isLogin) {
            logic.getData();
          }
        },
        child: EasyRefresh.builder(
          controller: logic.refreshController,
          scrollController: logic.refreshScroll,
          onRefresh: logic.getRefresh,
          header: Styles.refreshHeader(
              clamping: true, position: IndicatorPosition.locator),
          childBuilder: (context, physics) => ScrollConfiguration(
            behavior: const ERScrollBehavior(),
            child: ExtendedNestedScrollView(
                physics: physics,
                controller: logic.refreshScroll,
                pinnedHeaderSliverHeightBuilder: () => 40.5,
                headerSliverBuilder:
                    (BuildContext context, bool innerBoxIsScrolled) => [
                          const HeaderLocator.sliver(clearExtent: false),
                          if (logic.lbt.hasValue)
                            SliverToBoxAdapter(
                                child: QkdCarouselView(
                              key: Key("${DateTime.now()}"),
                              aspectRatio: 359 / 120,
                              radius: 8,
                              padding: 8,
                              needDot: (logic.lbt ?? []).length > 1,
                              carousels: logic.lbt ?? [],
                              tapType: "jhd_lbt",
                              needTitle: false,
                            ).paddingOnly(top: 8)),
                          SliverToBoxAdapter(child: tabBar())
                        ],
                body: Container(
                  color: Colours.greyF2F3F7,
                  child: ExtendedTabBarView(
                      controller: logic.tabController,
                      children: List.generate(logic.items.length,
                          (index) => page(logic.items[index], index, physics))),
                )),
          ),
        ),
      );
    });
  }

  Widget page(List<PlanForm>? entity, int index, ScrollPhysics physics) {
    return LoadingWidget<bool>(
      isLoading: entity == null,
      loading: CustomScrollView(
        physics: physics,
        slivers: [
          SliverList.list(children: List.generate(10, (index) => shimmerItem()))
        ],
      ),
      data: entity?.length == 0,
      noData: (index == 0 || index == 1) && !User.isLogin
          ? NoDataWidget(
              tip: "登录后才能关注比赛",
              buttonText: "去登录",
              needScroll: true,
              physics: physics,
              onTap: () => User.needLogin(() {}))
          : NoDataWidget(needScroll: true, physics: physics),
      child: () => CustomScrollView(
        physics: physics,
        slivers: [
          SliverList.list(
              children: entity
                      ?.where((element) => logic.currentStageNum(index) == 0
                          ? true
                          : element.stage == logic.currentStageNum(index))
                      .map((e) => item(e))
                      .toList() ??
                  [])
        ],
      ),
    );
  }

  Widget item(PlanForm entity) {
    var list = entity.tag?.split(",");
    String? firstTag;
    String? secondTag;
    if (list.hasValue && list?[0] != "") {
      firstTag = list![0];
      if (list.length > 1) {
        secondTag = list[1];
      }
    }
    return GestureDetector(
      onTap: () => Get.toNamed(Routes.userPage,
          arguments: entity.expertId,
          parameters: {"type": "2", "index": "jihuadan"}),
      child: Block(
          cardStyle: const CardStyle(
              margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
              padding: EdgeInsets.symmetric(vertical: 16, horizontal: 12)),
          child: Column(
            children: [
              Row(
                children: [
                  Expanded(
                    child: AvatarLabel.record(
                      avatarUrl: entity.expertLogo,
                      name: entity.expertName,
                      id: entity.expertId,
                      firstTag: firstTag,
                      secondTag: secondTag,
                      nameWeight: FontWeight.w500,
                      needJump: () => Get.toNamed(Routes.userPage,
                          arguments: entity.expertId,
                          parameters: {"type": "2", "index": "jihuadan"}),
                    ),
                  ),
                  const Spacer(),
                  FocusButton(
                    entity.expertFocus == true ? 1 : 0,
                    width: 68,
                    height: 28,
                    expertId: entity.expertId,
                    onTap: (focus) {
                      if ((focus == 1) != entity.expertFocus) {
                        logic.getData();
                      }
                    },
                  )
                ],
              ),
              Container(height: 16),
              Row(children: <Widget>[
                if (ModeConfig.expertRecord) ...[
                  Expanded(child: content(entity.maxRed, "最高连红")),
                  Expanded(child: content(entity.expertProfit, "近期回报")),
                ],
                Expanded(
                    child: content(
                        entity.issueState != 1
                            ? '${(entity.issue ?? 0) + 1}期'
                            : "${entity.issue ?? "0"}期 阶段${entity.stage.toChn}",
                        entity.issueState != 1
                            ? '未发布'
                            : entity.canBuy == true
                                ? "可购"
                                : "截止",
                        isRed: false))
              ]).paddingSymmetric(horizontal: 16)
            ],
          )),
    );
  }

  Widget content(String? value, String? title, {bool isRed = true}) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 8),
      height: 56,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          if (!isRed) Container(height: 2),
          QkdText(
            value ?? "",
            fontSize: isRed ? 18 : 14,
            color: isRed ? Colours.main : Colours.text,
            fontFamily: isRed ? "Din" : null,
            fontWeight: FontWeight.w500,
          ),
          if (!isRed) const Spacer(),
          QkdText(title ?? "", fontSize: 12, color: Colours.grey99)
        ],
      ),
    );
  }

  Widget tabBar() {
    return Container(
      decoration: BoxDecoration(
          border: Border(
              bottom: BorderSide(
                  color: logic.toTop ? Colours.greyEE : Colours.transparent,
                  width: 0.5))),
      child: Row(
        children: [
          Expanded(
            child: SizedBox(
              height: 40,
              child: Styles.tabbar(
                  controller: logic.tabController,
                  tabs: logic.tabs.map((e) => QkdText(e)).toList(),
                  onTap: (index) {
                    Utils.onEvent("jhdqhl", params: {"jhdqhl": "index"});
                  }),
            ),
          ),
          GestureDetector(
            onTap: () => logic.showDatePicker(),
            child: Container(
              height: 20,
              alignment: Alignment.center,
              padding: const EdgeInsets.symmetric(horizontal: 5),
              decoration: BoxDecoration(
                  border: Border.all(color: Colours.grey99, width: 0.5),
                  borderRadius: BorderRadius.circular(15)),
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    QkdText(logic.currentStage(logic.tabIndex),
                        needCenter: true, fontSize: 12),
                    const SizedBox(width: 2),
                    Padding(
                        padding: const EdgeInsets.only(top: 1),
                        child: Image.asset(
                            width: 6, Utils.getImgPath('down_arrow.png')))
                  ]),
            ),
          ).paddingOnly(right: 16)
        ],
      ),
    );
  }

  Widget shimmerItem() {
    return Block(
        cardStyle: const CardStyle(
            margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
            padding: EdgeInsets.symmetric(vertical: 16, horizontal: 12)),
        child: Column(
          children: [
            Row(
              children: [
                const ShimmerLoading(
                    width: 40, height: 40, shape: BoxShape.circle),
                Container(width: 8),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const ShimmerLoading(width: 102, height: 18),
                    Container(height: 2),
                    const ShimmerLoading(width: 65, height: 13)
                  ],
                ),
                const Spacer(),
                const ShimmerLoading(width: 68, height: 28, radius: 2)
              ],
            ),
            Container(height: 16),
            Row(
                children: List<Widget>.generate(
                        3,
                        (index) => const Expanded(
                            child: ShimmerLoading(width: 101, height: 36)))
                    .insertEvery(Container(width: 12)))
          ],
        ));
  }
}
